package br.com.dataphonebr.schedule;

import java.util.List;

import android.annotation.SuppressLint;
import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.support.v4.content.WakefulBroadcastReceiver;
import br.com.dataphonebr.util.AlarmUtil;
import br.com.dataphonebr.util.AlarmVO;
import br.com.dataphonebr.util.Util;

/**
 * When the alarm fires, this WakefulBroadcastReceiver receives the broadcast Intent 
 * and then starts the IntentService {@code SampleSchedulingService} to do some work.
 */
public class SampleAlarmReceiver extends WakefulBroadcastReceiver {

	public static final String ID_EXTRA_NAME = "ALARM_ATIV_ID";
	private AlarmManager alarmMgr;
    private PendingIntent alarmIntent;
	private AlarmUtil alarmUtil;
	private Util util = new Util();
	
    @Override
    public void onReceive(Context context, Intent intent) {   
    	alarmUtil = new AlarmUtil(context);
        Intent service = new Intent(context, SampleSchedulingService.class);
        int requestCode = intent.getExtras().getInt("requestCode");
        service.putExtra("requestCode", requestCode);
        startWakefulService(context, service);
        AlarmVO alarm = alarmUtil.getAlarmByRequestCode(requestCode);
        if (alarm != null && alarm.getId() != null && !alarm.getId().equals(AlarmUtil.ID_UPDATE))
        	util.vibrate(context);
//        Vibrator rr = (Vibrator) context.getSystemService(Context.VIBRATOR_SERVICE);
//        long milliseconds = 500; 
//        rr.vibrate(milliseconds);     
    }

    @SuppressLint("UseSparseArrays")
    public void setAlarm(Context context) {
    	alarmUtil = new AlarmUtil(context);
    	List<AlarmVO> myAlarms = alarmUtil.getAlarms();
        addAlarm(myAlarms, context);
        ComponentName receiver = new ComponentName(context, SampleBootReceiver.class);
        PackageManager pm = context.getPackageManager();
        pm.setComponentEnabledSetting(receiver, PackageManager.COMPONENT_ENABLED_STATE_ENABLED, PackageManager.DONT_KILL_APP);           
    }
    
    public void addAlarm(List<AlarmVO> myAlarms, Context context){
    	alarmUtil = new AlarmUtil(context);
		if (myAlarms != null && !myAlarms.isEmpty()){
			for (AlarmVO theAlarm : myAlarms) {
				if (alarmUtil.isValidAlarm(theAlarm)){
					alarmMgr = (AlarmManager)context.getSystemService(Context.ALARM_SERVICE);
					System.out.println("-----------------------");
					System.out.println("Codigo: "+theAlarm.getId());
					System.out.println("Hora: "+util.timeToString(theAlarm.getTime()));
					System.out.println("Hora2: "+theAlarm.getAlarmFromCalendar().getTimeInMillis());
					System.out.println("Hora3: "+theAlarm.getAlarmFromCalendar().getTime());
					System.out.println("Request code: "+theAlarm.getRequestCode());
					System.out.println("-----------------------");
					Intent intent = new Intent(context, SampleAlarmReceiver.class);
					intent.putExtra("requestCode", theAlarm.getRequestCode());
					alarmIntent = PendingIntent.getBroadcast(context, theAlarm.getRequestCode(), intent, PendingIntent.FLAG_UPDATE_CURRENT);
					alarmMgr.set(AlarmManager.RTC_WAKEUP, theAlarm.getAlarmFromCalendar().getTimeInMillis(), alarmIntent);
				}
			}
		}
    }
    
    public void removeAlarm(List<AlarmVO> myAlarms, Context context){
    	if (myAlarms != null && !myAlarms.isEmpty()){
    		for (AlarmVO theAlarm : myAlarms) {
    			if (theAlarm != null){
					alarmMgr = (AlarmManager)context.getSystemService(Context.ALARM_SERVICE);
					Intent intent = new Intent(context, SampleAlarmReceiver.class);
					alarmIntent = PendingIntent.getBroadcast(context, theAlarm.getRequestCode(), intent, 0);
					System.out.println("Excluido alarm "+theAlarm.getId()+"-"+theAlarm.getRequestCode()+"-"+theAlarm.getTime());
					if (alarmIntent != null){
						alarmMgr.cancel(alarmIntent);
    				}
    			}
    		}
    	}
    }
    
    /**
     * Cancels the alarm.
     * @param context
     */
    public void cancelAlarm(Context context) {
    	alarmUtil = new AlarmUtil(context);
    	List<AlarmVO> myAlarms = alarmUtil.getAlarms();
    	removeAlarm(myAlarms, context);
        if (alarmMgr!= null) {
            alarmMgr.cancel(alarmIntent);
        }
        
        // Disable {@code SampleBootReceiver} so that it doesn't automatically restart the 
        // alarm when the device is rebooted.
        ComponentName receiver = new ComponentName(context, SampleBootReceiver.class);
        PackageManager pm = context.getPackageManager();

        pm.setComponentEnabledSetting(receiver, PackageManager.COMPONENT_ENABLED_STATE_DISABLED, PackageManager.DONT_KILL_APP);
    }
}
